﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PwdMgr.DataAccess;
using PwdMgr.PwdMgrService.Sessions;
using PwdMgr.Utility.Exceptions;
using PwdMgr.CommonContract;
using PwdMgr.Utility;
using PwdMgr.Utility.Crypto;

namespace PwdMgr.PwdMgrService.UserAuthentication
{
    public class DefaultAuthService : IAuth
    {
        public IDataAccessManager DAMgr { get; set; }

        public int Login(string username, string password)
        {
            if (string.IsNullOrEmpty(username))
                throw new ArgumentNullException("username");

            if (string.IsNullOrEmpty(password))
                throw new ArgumentNullException("password");

            UserInfo user = null;
            password = CryptoUtil.MD5(password);
            using (IDataAccess ins = DAMgr.CreateInstance(true))
            {
                user = ins.GetUser(username, password);
            }
            if (user != null)
            {
                return user.UserID;
            }
            throw new InvalidUsernamePasswordException();
        }

        public void CreateUser(UserInfo userInfo)
        {
            ThrowUtil.ArgumentNullException(userInfo, "userInfo");
            ThrowUtil.ThrowIfEmptyOrWhiteSpace(userInfo.UserName);
            ThrowUtil.ThrowIfEmptyOrWhiteSpace(userInfo.Password);

            userInfo.Password = CryptoUtil.MD5(userInfo.Password);
            userInfo.Answer = CryptoUtil.MD5(userInfo.Answer);
            using (IDataAccess ins = DAMgr.CreateInstance(true))
            {
                int count = ins.QueryUserInfoCount(userInfo.UserName);
                if (count > 0)
                {
                    throw new UserAlreadyExistException();
                }
                ins.CreateUserInfo(userInfo);
            }
        }
    }
}
